<template>
  <div class="w-full" v-loading="loading">
    <el-button type="primary" class="mb-16px" @click="doEdit()">新增</el-button>
    <el-table :data="processedList">
      <el-table-column label="联系人" prop="contactUser"></el-table-column>
      <el-table-column label="联系电话" prop="contactUserMobile"></el-table-column>
      <el-table-column label="单价" prop="goodsPrice"></el-table-column>
      <el-table-column label="到货时间" :formatter="formatArriveTime"></el-table-column>
      <el-table-column label="过期时间" :formatter="formatExpireTime"></el-table-column>
      <el-table-column label="交付地点" prop="goodsAddress"></el-table-column>
      <el-table-column label="销售数量" prop="goodsNumber"></el-table-column>
      <el-table-column label="货源性质" prop="goodsType">
        <template #default="{ row }">
          <span>{{ goodsTypeText(row.goodsType) }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="信息大图"
          prop="infoPicUrl"
          width="100"
      >
        <template #default="{ row }">
          <img
              v-if="row.infoPicUrl"
              :src="row.infoPicUrl"
              alt="信息大图"
              style="width: 60px; height: 60px; object-fit: cover;"
          />
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column label="品牌" prop="brandName"></el-table-column>
      <el-table-column label="型号" prop="modelName"></el-table-column>
      <el-table-column label="配置参数">
        <template #default="{ row }">
          <div v-html="truncateParamDesc(row.paramDesc)"></div>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="120">
        <template #default="{ row }">
          <el-button
              :type="row.status === 1 ? 'success' : 'danger'"
              @click="() => toggleGoods(row)"
          >
            {{ row.status === 1 ? '上架' : '下架' }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" prop="action">
        <template #default="{ row }">
          <el-button type="text" @click="doEdit(row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-show="list.length"
        class="w-full justify-end mt-12px"
        :total="total"
        layout="total, sizes, prev, pager, next"
        v-model:current-page="page.pageNum"
        v-model:page-size="page.pageSize"
        :page-sizes="[15, 30, 60, 120]"
    ></el-pagination>
    <Empty v-if="!list.length" />
    <el-dialog
        v-model="addVisible"
        width="60vw"
        :title="isAdd ? '新增' : '编辑'"
        :close-on-click-modal="false"
        @close="handleClose"
    >
      <el-form
          ref="formRef"
          :model="addData"
          :rules="rules"
          label-width="100"
          class="py-16px px-32px"
      >
        <el-form-item label="品牌" prop="brandName">
          <el-input v-model="addData.brandName" placeholder="请输入品牌"></el-input>
        </el-form-item>
        <el-form-item label="型号" prop="modelName">
          <el-input v-model="addData.modelName" placeholder="请输入型号"></el-input>
        </el-form-item>
        <el-form-item label="货源性质" prop="goodsType">
          <el-radio-group v-model="addData.goodsType">
            <el-radio :label="1">现货</el-radio>
            <el-radio :label="2">期货</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="配置参数" prop="paramDesc">
          <el-input
              type="textarea"
              v-model="addData.paramDesc"
              placeholder="请输入配置参数"
              :rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item label="信息大图" prop="infoPicUrl">
          <ShardUpload
              v-model="addData.infoPicUrl"
              :limit="1"
              :fileSize="50"
              accept="image/*,video/*"
              :fileType="['png', 'jpg', 'jpeg', 'mp4', 'avi']"
              :extraTips="addData.infoType === 1 ? '轮播图尺寸： 1920 * 620' : ''"
              @change="handleFileChange"
              @uploadSuccess="uploadSuccess"
          />
        </el-form-item>
        <el-form-item label="销售数量" prop="goodsNumber">
          <el-input
              v-model="addData.goodsNumber"
              placeholder="请输入销售数量"
              :maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="单价" prop="goodsPrice">
          <el-input
              v-model="addData.goodsPrice"
              placeholder="请输入单价"
              :maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item  v-if="addData.goodsType === 2" label="到货时间" prop="arriveTime">
          <el-date-picker
              style="width: 60%"
              type="datetime"
              v-model="addData.arriveTime"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择到货时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item v-if="addData.goodsType === 2"  label="批次量/次" prop="batchNum">
          <el-input
              v-model="addData.batchNum"
              placeholder="请输入每次交货的批次量"
              :maxlength="11"
              type="number"
          ></el-input>
        </el-form-item>
        <el-form-item  v-if="addData.goodsType === 1" label="信息过期时间" prop="expireTime">
          <el-date-picker
              style="width: 60%"
              type="datetime"
              v-model="addData.expireTime"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="联系人" prop="contactUser">
          <el-input
              v-model="addData.contactUser"
              placeholder="请输入联系人"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactUserMobile">
          <el-input
              v-model="addData.contactUserMobile"
              placeholder="请输入手机号"
              :maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="交付地点" prop="goodsAddress">
          <el-input
              v-model="addData.goodsAddress"
              placeholder="请输入交付地点"
              :maxlength="11"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addVisible = false">取消</el-button>
        <el-button
            type="primary"
            :loading="confirmLoading"
            @click="handleSubmit"
        >确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, watch, computed} from 'vue';
import {useLoading, usePage} from '@/hooks';
import {useUserStore} from '@/store';
import {phoneValidator} from '@/utils/valid';
import $api from '@/api/hardware';
import {ElMessage} from 'element-plus';
import ShardUpload from '@/components/FileUpload/shardUpload.vue';

const userStore = useUserStore();
const companyId = computed(() => userStore.userInfo?.companyId);

const {loading, setLoading} = useLoading();
const {page, total} = usePage(10);

const list = ref([]);

const getList = async () => {
  setLoading(true);
  try {
    const queryParams = {
      ...page.value,
      companyId: companyId.value,
    };
    const {data, total: resTotal} = await $api.getGoodsList(queryParams);
    list.value = data;
    total.value = resTotal;
  } finally {
    setLoading(false);
  }
};

watch(
    () => page.value,
    () => {
      getList();
    },
    {
      deep: true,
    }
);

const formRef = ref();
const isAdd = ref(false);
const addVisible = ref(false);
const detailVisible = ref(false);
const {loading: confirmLoading, setLoading: setConfirmLoading} = useLoading();
const addData = ref({
  goodsName: "",
  contactUser: "",
  contactUserMobile: "",
  modelName: "",
  goodsPrice: "",
  arriveTime: "",
  expireTime: "",
  goodsAddress: "",
  goodsNumber: "",
  goodsType: "",
  paramDesc: "",
  infoPicUrl: "",
  status:0,
});
const detailData = ref({});

const rules = reactive({
  goodsName: [{required: true, message: "请输入供应信息名"}],
  contactUser: [{required: true, message: "请输入联系人"}],
  contactUserMobile: [{required: true, validator: phoneValidator}],
  modelName: [{required: true, message: "请输入型号"}],
  infoPicUrl: [{required: true, message: "请上传信息大图"}],
  goodsNumber: [
    {required: true, message: "请输入销售数量"},
    {pattern: /^[0-9]*$/, message: "销售数量只能输入数字"}
  ],
  goodsPrice:[
    {required: true, message: "请输入单价"},
    {pattern: /^[0-9]*$/, message: "价格只能输入数字"}
  ],
});

const handleClose = () => {
  formRef.value.resetFields();
};

const doEdit = (row) => {
  isAdd.value = !row;
  if (row) addData.value = JSON.parse(JSON.stringify(row));
  addVisible.value = true;
};

const handleAdd = () => {
  isAdd.value = true;
  addData.value = {
    goodsName: "",
    contactUser: "",
    contactUserMobile: "",
    modelName: "",
    goodsPrice: "",
    arriveTime: "",
    expireTime: "",
    goodsAddress: "",
    goodsNumber: 0,
    goodsType: 0,
    paramDesc: "",
    infoPicUrl: "",
    status: 0,
  };
  addVisible.value = true;
};

const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      setConfirmLoading(true);
      const apiName = isAdd.value ? "createGoods" : "updateGoods";
      try {
        await $api[apiName](addData.value);
        ElMessage.success(isAdd.value ? "新增成功" : "编辑成功");
        getList();
        addVisible.value = false;
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error("提交失败");
      } finally {
        setConfirmLoading(false);
      }
    }
  });
};

const toggleGoods = async (row) => {
  const updatedStatus = row.status === 1 ? 0 : 1;

  try {
    await $api.toggleGoods({id: row.id, status: updatedStatus});
    ElMessage.success(`状态已更新为 ${updatedStatus === 1 ? "上架" : "下架"}`);
    getList();
  } catch (error) {
    ElMessage.error("状态更新失败");
  }
};

const viewDetail = (row) => {
  detailData.value = JSON.parse(JSON.stringify(row));
  detailVisible.value = true;
};

const uploadSuccess = (file) => {
  if (file && file.url) {
    addData.value.infoPicUrl = file.url;
  } else {
    console.error('文件 URL 无效:', file);
  }
};

const handleFileChange = (file) => {

};

const goodsTypeText = (type) => {
  return type === 1 ? '现货' : '期货';
};

const formatArriveTime = (row) => {
  return row.goodsType === 1 ? '' : row.arriveTime;
};

const formatExpireTime = (row) => {
  return row.goodsType === 2 ? '' : row.expireTime;
};

const truncateParamDesc = (desc) => {
  const maxLength = 10; // 设置要显示的最大字符数
  return desc.length > maxLength ? `${desc.slice(0, maxLength)}...` : desc;
};

const processedList = computed(() => {
  return list.value.map(item => ({
    ...item,
    arriveTime: formatArriveTime(item),
    expireTime: formatExpireTime(item),
  }));
});

onMounted(() => {
  getList();
});
</script>

<style scoped>
.el-form-item__extra {
  color: #999;
  font-size: 12px;
}
</style>
